<template>
    <div class="user-search">
        <van-nav-bar
            left-arrow
            :fixed="true"
            @click-left="$router.back(-1)"
            style="color:#fff;">
            <div slot="title" class="van-search"
                 style="background: rgb(255, 153, 0); display: inline-block; width: 100%;">
                <div class="van-cell van-field">
                    <input type="search" autofocus ref="inputs" :placeholder="$t('m.SearchinUsers')"
                           v-model="searchUserTerm" @search="onSearchUser" class="search-input"/>
                </div>
            </div>
            <div class="search-submit-box" slot="right">
                <van-button size="small" class="search-submit" @click="onSearchUser">{{$t('m.Search')}}</van-button>
            </div>
        </van-nav-bar>

        <van-list
            v-model="userLoading"
            :finished="finished"
            loading-text=" "
            @load="getUserList"
            class="user-outer-wraper"
        >
            <div class="user-wraper" v-for="(item,index) in userData" :key="index">
                <div class="user-photo"
                     @click="$router.push({path:'user/other-account',query:{
                     userId:`${item.id}`
                     }})">
                    <img :src="item.photo||defaultUserPhoto" alt=""
                         style="width:47px;height:47px;borderRadius:50%;"
                         @error="userPhotoError(item)">
                </div>
                <div class="user-info"
                     @click="$router.push({path:'user/other-account',query:{
                     userId:`${item.id}`
                     }})">
                    <p class="name">{{item.name}}</p>
                    <p class="followers">{{item.followed_count||0}} followers</p>
                </div>
                <div class="following" v-if="item.ifFollowed==1" @click="userUnFollow(item.id)"><p>{{$t('m.Following')}}</p></div>
                <div class="follow" v-else @click="userFollow(item.id)"><p>{{$t('m.Follow')}}</p></div>
            </div>
        </van-list>
        <div v-if="finished && !userLoading" class="no-more">{{$t('m.Nomore')}}~</div>
    </div>
</template>
<script>
    import {searchUserList, followUser, unFollowUser} from '../static/api/guc_api'
    import Qs from 'qs'


    export default {
        name: 'searchUser',
        data() {
            return {
                defaultUserPhoto: '../static/img/images/user-pto.png',
                searchUserTerm: '',
                pageData: {
                    pageNum: 1,
                    pageSize: 10,
                },
                pageInfo: {
                    totalCount: 0,
                    totalPages: 0
                },
                userLoading: false,
                finished: false,
                userData: [],
            }
        },
        methods: {
            userPhotoError(item) {
                item.photo = require('../static/img/images/user-pto.png');
            },
            getUserList(pageNum) {
                if (pageNum == 1) {
                    this.pageData.pageNum = 1;
                    this.userData = [];
                }
                let searchForm = {};
                searchForm.name = this.searchUserTerm
                // 默认按照时间排序
                searchForm.sort = 'create_time desc'
                searchForm.pageNum = this.pageData.pageNum
                searchForm.pageSize = this.pageData.pageSize
                // let params = Qs.stringify(searchForm, {arrayFormat: 'repeat'})
                searchUserList(searchForm).then((res) => {
                    console.log(res)
                    if (res.data.errorID == 0) {
                        let dataList = res.data.object.list || []
                        // // 刷新列表 or 加载更多
                        if (this.pageData.pageNum == 1) {
                            window.scrollTo(0, 0)
                            this.userData = dataList
                            this.finished = false;
                        } else {
                            this.userData = this.userData.concat(dataList)
                        }
                        // console.log(this.userData, 'this.userData')
                        // // 分页信息配置
                        this.pageInfo.totalPages = res.data.object.pages
                        this.pageInfo.totalCount = res.data.object.total
                        this.pageData.pageNum = this.pageData.pageNum + 1
                        if (this.pageData.pageNum > this.pageInfo.totalPages) {
                            this.finished = true
                        }
                        this.userLoading = false;
                    } else {
                        this.$toast(res.data.message)
                        this.finished = true
                        this.userLoading = false;
                    }

                }).catch((e) => {
                    this.$toast('No internet, please try again')
                    this.finished = true
                    this.userLoading = false
                })
            },
            userFollow(id) {
                console.log(id)
                let data = {
                    'toUserId': id,
                }
                let params = Qs.stringify(data)
                let config = {
                    'Content-Type': 'multipart/form-data'
                }
                this.$toast.loading({
                    mask: true,
                    message: 'Loading...',
                    duration: 0
                })
                followUser(params, config).then(res => {
                    console.log(res)
                    this.$toast.clear()
                    if (res.data.errorID === 0) {
                        this.getUserList(1)
                    }
                    else if (res.data.errorID === 100004) {
                        this.$router.push('/login-register/loginregister')
                    }
                    else {
                        this.$toast(res.data.message)
                    }
                })
                    .catch(error => {
                        this.$toast.clear()
                        this.$toast('No internet, please try again')
                    })
            },
            userUnFollow(id) {
                let data = {
                    'toUserId': id,
                }
                let params = Qs.stringify(data)
                let config = {
                    'Content-Type': 'multipart/form-data'
                }
                this.$toast.loading({
                    mask: true,
                    message: '加载中...',
                    duration: 0
                });
                unFollowUser(params, config).then(res => {
                    console.log(res)
                    this.$toast.clear()
                    if (res.data.errorID === 0) {
                        this.getUserList(1)
                    }
                    else if (res.data.errorID === 100004) {
                        this.$router.push('/login-register/loginregister')
                    }
                    else {
                        this.$toast(res.data.message)
                    }
                })
                    .catch(error => {
                        this.$toast.clear()
                        this.$toast('No internet, please try again')
                    })
            },
            onSearchUser() {
            this.getUserList(1)
                //把search in Tolymoly的搜索内容存入本地存储 最多20条
                // window.localStorage.removeItem('gogoSearchHistory')
                let val = window.localStorage.getItem('userSearchHistory')
                if (val != null) {
                    val = JSON.parse(val)
                    if (this.searchUserTerm) {
                        //重复的数据不能重复添加 最新搜索的放在最前面
                        let index = val.findIndex((item) => {
                            return item == this.searchUserTerm
                        })
                        // 如果已经存在 在之前的位置删掉 插入最后面
                        if (index > -1) {
                            val.splice(index, 1)
                            val.push(this.searchUserTerm)
                        }
                        // 如果不存在 直接插入
                        else {
                            val.push(this.searchUserTerm)
                        }
                        // 然后判断数组长度
                        if (val.length > 20) {
                            val.shift()
                        }
                        window.localStorage.setItem('userSearchHistory', JSON.stringify(val));
                    }
                }
                else {
                    let arr=[]
                    if(this.searchTerm){
                        arr=[this.searchTerm]
                    }
                    window.localStorage.setItem('userSearchHistory', JSON.stringify(arr));
                }
            },
        },
        mounted() {
            this.searchUserTerm = this.$route.query.searchTerm || ''
        },
    }
</script>
<style>
    .user-search {
        width: 100%;
    }

    .user-search .van-nav-bar {
        background-color: #FF9900;
        color: #fff;
    }

    .user-search .van-nav-bar .van-icon {
        color: #fff;
        margin-right: 15px;
        font-size: 18px;
    }

    .user-search .van-search .van-cell {
        border-radius: 0;
    }

    .user-search .van-nav-bar .van-icon.van-icon-search {
        color: #999;
    }

    .user-search .van-nav-bar__title {
        height: 100%;
        margin-left: 50px;
        margin-right: 90px;
    }

    .user-search .van-search {
        padding: 3px 0;
    }

    .user-search .van-search .van-icon-search {
        left: 10px;
    }

    .user-wraper {
        display: flex;
        padding: 10px 0;
        align-items: center;
        width: 100%;
    }

    .user-wraper .user-photo {
        width: 47px;
        height: 47px;
        border-radius: 50%;
        margin-right: 10px;
        margin-left: 3%;
        flex-shrink: 0;
    }

    .user-wraper .user-info {
        flex: 1;
    }

    .user-wraper .user-info p {
        margin: 0;
        padding: 0;
        font-size: 14px;
        font-family: 微软雅黑;
        line-height: 20px;
    }

    .user-wraper .user-info .name {
        margin-bottom: 5px;
        font-weight: 400;
        color: rgb(0, 0, 0);
    }

    .user-wraper .user-info .followers {
        margin-top: 5px;
        color: rgb(102, 102, 102);
    }

    .user-wraper .follow {
        flex-shrink: 0;
        border: solid 1px rgb(255, 153, 0);
        box-sizing: border-box;
        text-align: center;
        width: 62px;
        height: 30px;
        border-radius: 4px;
        margin-right: 3%;
    }

    .user-wraper .following {
        flex-shrink: 0;
        border: solid 1px rgb(255, 153, 0);
        box-sizing: border-box;
        text-align: center;
        width: 70px;
        height: 30px;
        border-radius: 4px;
        margin-right: 3%;
    }

    .user-wraper .follow p {
        font-size: 14px;
        font-weight: 400;
        color: rgb(255, 153, 0);
        padding: 0px;
        margin: 0px;
        line-height: 28px;
    }

    .user-wraper .following p {
        font-size: 14px;
        font-weight: 400;
        background: rgb(255, 153, 0);
        color: rgb(255, 255, 255);
        padding: 0px;
        margin: 0px;
        line-height: 28px;
    }

    .user-outer-wraper {
        margin-top: 46px;
        width: 100%;
    }

    .no-more {
        border-top: 1px solid #F2F2F2;
        height: 50px;
        line-height: 50px;
        color: #909399;
        text-align: center;
    }

    .search-input {
        width: 100%;
        border: 0;
        font-size: 14px;
        padding: 0;
        height: 24px;
        line-height: 24px;
    }

    .search-submit-box .search-submit {
        width: 100%;
        border-radius: 5px;
    }
</style>

